<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
/**
 * 主动推送文章到百度
 * 
 * @package AutoSubmitToBaidu
 * @author joinerXing
 * @version 1.1.0
 * @link http://www.niaoge.vip
 */
class AutoSubmitToBaidu_Plugin implements Typecho_Plugin_Interface
{
    public static function activate()
    {
        Typecho_Plugin::factory('Widget_Contents_Post_Edit')->write = array('AutoSubmitToBaidu_Plugin', 'contentsend');
        Typecho_Plugin::factory('Widget_Contents_Page_Edit')->write = array('AutoSubmitToBaidu_Plugin', 'pagesend');
		return _t('主动推送文章到百度启用成功，请配置推送时的token');
    }
	
	public static function contentsend($contents,$edit)
	{
		self::send('archives/'.$contents['slug'].'.html');
		return $contents;
	}
	
	public static function pagesend($contents,$edit)
	{
		self::send($contents['slug'].'.html');
		return $contents;
	}
	
    public static function send($uri)
	{
		$options = Helper::options();
		$url = $options->siteUrl;
		$domin = str_replace(array('http://','https://','/'),'',$url);
		$url .= $uri;
		$plugin_config = $options->plugin('AutoSubmitToBaidu');
		if(empty($plugin_config->token))return _t('请先设置token！');
		$urls = array($url);
		$api = 'http://data.zz.baidu.com/urls?site='.$domin.'&token='.$plugin_config->token;
		$ch = curl_init();
		$options =  array(
			CURLOPT_URL => $api,
			CURLOPT_POST => true,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_POSTFIELDS => implode("\n", $urls),
			CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
		);
		curl_setopt_array($ch, $options);
		$result = curl_exec($ch);
		return true;
		//return file_put_contents('/tmp/autobaidu.log',json_encode(array($result,$domin,$url,$plugin_config->token)),FILE_APPEND);
	}
	
    public static function deactivate()
    {
        return '插件卸载成功';
    }
	
    public static function config(Typecho_Widget_Helper_Form $form)
    {
		$element = new Typecho_Widget_Helper_Form_Element_Textarea('token', NULL, "",_t('推送时的token'), _t('请登录百度站长平台获取'));
        $form->addInput($element);
	}

    public static function personalConfig(Typecho_Widget_Helper_Form $form)
    {
	}
}